package com.itheima.search.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.search.dto.SearchDto;
import com.itheima.search.mapper.ApAssociateWordsMapper;
import com.itheima.search.pojo.ApAssociateWords;
import com.itheima.search.service.ApAssociateWordsService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.trie4j.patricia.PatriciaTrie;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @description <p>联想词 业务实现</p>
 *
 * @version 1.0
 * @package com.itheima.search.service.impl
 */
@Service
public class ApAssociateWordsServiceImpl extends ServiceImpl<ApAssociateWordsMapper, ApAssociateWords> implements ApAssociateWordsService {

    /**
     * 关联词搜索
     *
     * @param dto
     * @return
     */
    @Override
    public List<String> search(SearchDto dto) {
        // 构建查询条件
        LambdaQueryWrapper<ApAssociateWords> lqw = new LambdaQueryWrapper<>();
        lqw.likeRight(!StringUtils.isEmpty(dto.getSearchWords()), ApAssociateWords::getAssociateWords, dto.getSearchWords());
        List<ApAssociateWords> list = list(lqw);

        List<String> stringList = new ArrayList<>();
        if(!CollectionUtils.isEmpty(list)){
            stringList = list.stream().map(ApAssociateWords::getAssociateWords).collect(Collectors.toList());
        }
        return stringList;
    }

    @Resource
    private PatriciaTrie trie;

    @Override
    public List<String> search2(SearchDto dto) {
        List<String> list = new ArrayList<>();
        if(!StringUtils.isEmpty(dto.getSearchWords())){
            if (!trie.contains(dto.getSearchWords())) {
                trie.insert(dto.getSearchWords());
            }
            list = (List<String>)trie.predictiveSearch(dto.getSearchWords());
        }

        return list;
    }
}
